package com.gitee.ricesugar.mall.servlets;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.ricesugar.mall.model.POJO.DTO.CartItemDTO;
import com.gitee.ricesugar.mall.model.Service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "BuyProductServlet", value = "/buy")
public class BuyProductServlet extends HttpServlet {

    private OrderService orderService;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            orderService = new OrderService();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        StringBuilder json = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            json.append(line);
        }

        ObjectMapper mapper = new ObjectMapper();
        CartItemDTO item = mapper.readValue(json.toString(), CartItemDTO.class);

        try {
            orderService.buyItem(item);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
